#include "PluginSQLite.h"
#include <LuaManager.h>

PluginSQLite::PluginSQLite()
{
	m_pDatabase = 0;
	m_sError = 0;
}

PluginSQLite::~PluginSQLite()
{
	if (m_pDatabase)
	{
		sqlite3_free(m_sError);
		m_sError = 0;
		sqlite3_close(m_pDatabase);
		m_pDatabase = 0;
	}
}

int PluginSQLite::Init()
{
	LuaManager::GetInstance().GetLua().new_usertype<PluginSQLite>("PluginSQLite",
		sol::constructors<PluginSQLite()>(),
		"Open", &PluginSQLite::Open,
		"Close", &PluginSQLite::Close,
		"Exec", &PluginSQLite::Exec
		);

	return 1;
}

int PluginSQLite::Shutdown()
{
	return 1;
}

bool PluginSQLite::Open(const char * path)
{
	if (sqlite3_open(path, &m_pDatabase) != SQLITE_OK)
	{
		sqlite3_close(m_pDatabase);
		return false;
	}
	return true;
}

void PluginSQLite::Close()
{
	sqlite3_free(m_sError);
	m_sError = 0;
	sqlite3_close(m_pDatabase);
	m_pDatabase = 0;
}

static int callback(void * NotUsed, int argc, char ** argv, char ** azColName)
{
	int i;
	for (i = 0; i < argc; i++)
	{
		printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
	}
	return 0;
}

std::string PluginSQLite::Exec(const char* exec)
{
	std::string error = 0;

	if (sqlite3_exec(m_pDatabase, exec, callback, 0, &m_sError) != SQLITE_OK)
	{
		error = m_sError;
		sqlite3_free(m_sError);
		m_sError = 0;
	}

	return error;
}
